package com.ktg.web.controller.system;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.ktg.common.exception.BussinessException;
import com.ktg.system.utils.SecurityUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.system.domain.SysDataSource;
import com.ktg.system.service.ISysDataSourceService;
import com.ktg.common.utils.poi.ExcelUtil;
import com.ktg.common.core.page.TableDataInfo;

/**
 * 数据源Controller
 * 
 * @author byteco
 * @date 2022-08-26
 */
@Slf4j
@RestController
@RequestMapping("/system/dataSource")
public class SysDataSourceController extends BaseController
{
    @Autowired
    private ISysDataSourceService sysDataSourceService;

    @Autowired
    private DruidDataSourceCreator druidDataSourceCreator;

    @Autowired
    private DataSource dataSource;
    /**
     * 查询数据源列表
     */
    @PreAuthorize("@ss.hasPermi('system:dataSource:list')")
    @GetMapping("/list")
    public Result<IPage<SysDataSource>> list(SysDataSource sysDataSource,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        Page<SysDataSource> page = new Page<SysDataSource>(pageNo, pageSize);
        IPage<SysDataSource> pageList = sysDataSourceService.queryPageList(sysDataSource,page);
        return Result.OK(pageList);
    }

    /**
     * 导出数据源列表
     */
    @PreAuthorize("@ss.hasPermi('system:dataSource:export')")
    @Log(title = "数据源", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysDataSource sysDataSource)
    {
        IPage<SysDataSource> list = sysDataSourceService.queryPageList(sysDataSource,null);
        ExcelUtil<SysDataSource> util = new ExcelUtil<SysDataSource>(SysDataSource.class);
        util.exportExcel(response, list.getRecords(), "数据源数据");
    }

    /**
     * 获取数据源详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dataSource:query')")
    @GetMapping(value = "/{id}")
    public Result<SysDataSource> getInfo(@PathVariable("id") String id)
    {
        return Result.OK(sysDataSourceService.getInfo(id));
    }

    /**
     * 新增数据源
     */
    @PreAuthorize("@ss.hasPermi('system:dataSource:add')")
    @Log(title = "数据源", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<String> add(@RequestBody SysDataSource sysDataSource)
    {
        return sysDataSourceService.insert(sysDataSource);
    }

    /**
     * 修改数据源
     */
    @PreAuthorize("@ss.hasPermi('system:dataSource:edit')")
    @Log(title = "数据源", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<String> edit(@RequestBody SysDataSource sysDataSource)
    {
        sysDataSourceService.update(sysDataSource);
        return Result.OK("编辑成功！");
    }

    /**
     * 删除数据源
     */
    @PreAuthorize("@ss.hasPermi('system:dataSource:remove')")
    @Log(title = "数据源", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public Result<String> remove(@PathVariable String[] ids)
    {
        List<String> idList = Arrays.asList(ids);
        idList.forEach(item-> {
            SysDataSource sysDataSource = sysDataSourceService.getById(item);
            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
            ds.removeDataSource(sysDataSource.getCode());
        });
        sysDataSourceService.delete(ids);
        return Result.OK("删除成功！");

    }

    @PostMapping("/syncDs")
    @ApiOperation("同步Druid数据源至DynamicRoutingDataSource")
    public Result<?> syncDs(@Validated @RequestBody SysDataSource sysDataSource) {

        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        try {
            if (CollectionUtils.isNotEmpty(ds.getDataSources().keySet())) {
                if (ds.getDataSources().keySet().contains(sysDataSource.getCode())) {
                    ds.removeDataSource(sysDataSource.getCode());
                }
            }
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setPoolName(sysDataSource.getCode());
            dataSourceProperty.setDriverClassName(sysDataSource.getDbDriver());
            dataSourceProperty.setUrl(sysDataSource.getDbUrl());
            dataSourceProperty.setUsername(sysDataSource.getDbUsername());
            String decodedStr = SecurityUtil.jiemi(sysDataSource.getDbPassword());
            dataSourceProperty.setPassword(decodedStr);
            dataSourceProperty.setLazy(true);
            DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
            ds.addDataSource(sysDataSource.getCode(), dataSource);
        }catch (Exception ex){
            log.error("同步Druid数据源至DynamicRoutingDataSource出错：",ex);
        }

        return Result.OK(ds.getDataSources().keySet());
    }



    @PostMapping("/cancelSyncDs")
    @ApiOperation("删除动态数据源")
    public Result<?> cancelSyncDs(@RequestBody SysDataSource sysDataSource) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(sysDataSource.getCode());
        return Result.OK("成功移除动态数据源");
    }
}
